package cn.hl.service.impl;

import cn.hl.domain.User;
import cn.hl.dto.MovieTicketDto;
import cn.hl.enums.GlobalExceptionCode;
import cn.hl.feign.MovieServer;
import cn.hl.mapper.UserMapper;
import cn.hl.result.JSONResult;
import cn.hl.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.LinkedHashMap;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hulan
 * @since 2022-09-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MovieServer movieServer;

    @Override
    public JSONResult buyMovieTicketById(MovieTicketDto movieTicketDto) {
        User user = userMapper.selectById(movieTicketDto.getUserId());
        JSONResult jsonResult = movieServer.get(movieTicketDto.getMovieTicketId());
        Object priceObj = ((LinkedHashMap) jsonResult.getData()).get("price");
        BigDecimal price = new BigDecimal(priceObj.toString());
        if (-1 == user.getBalance().compareTo(price)) {
            return JSONResult.error(GlobalExceptionCode.OUT_OF_BALANCE);
        }
        user.setBalance(user.getBalance().subtract(price.multiply(new BigDecimal(movieTicketDto.getCount()))));
        movieServer.buyMovieTicketById(movieTicketDto);
        userMapper.updateById(user);
        return JSONResult.success();
    }

    @Override
    public boolean insert(User user) {
        boolean insert = super.insert(user);
        movieServer.sendMovieTicket(user.getId());
        return insert;
    }
}
